import java.net.*;
import java.io.*;

// Simple Multi Chatting Client
public class TestClient extends Thread
{
	private Socket s;
	private String host, chatID;
	private int port;
	private InputStream is;
	private OutputStream os;
	private DataInputStream dis;
	private PrintStream dos;
	private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

	public TestClient()
	{
		ready();
	}

	private void ready()
	{
		try{
			input();
			s = new Socket(host, port);
			System.out.println("Connect the Server[" + host + "] successfully.");
			is = s.getInputStream();
			dis = new DataInputStream(is);
			os = s.getOutputStream();
			dos = new PrintStream(os);
			start();
			speak();
		}catch(UnknownHostException une){
			System.out.println("Can not find the Host("+host+").");
			ready();
		}catch (IOException e){
			System.out.println("connect failed");
			ready();
		}finally{
			allClose();
		}
	}

	private void input()
	{
		try{
			System.out.print("Going to connect server Host(IP) : ");
			host = br.readLine();
			if(host != null) host = host.trim();
			if(host.equals("")) host = "127.0.0.1";
			
			System.out.print("Going to connect server PORT(default:7000) : ");
			String portStr = "";
			portStr = br.readLine();
			if(portStr != null) portStr = portStr.trim();
			if(portStr.equals("")) portStr = "7000";
			port = Integer.parseInt(portStr);
			if(port < 0 || port > 65535)
			{
				System.out.println("Port number has to be 0~65535.");
				input();
			}
			System.out.print("Chatting ID : ");
			chatID = br.readLine();
			if(chatID != null) chatID = chatID.trim();
			if(chatID.equals("")) chatID = "Client";
		}catch (IOException e){
			System.out.println("Wrong input. Try again.");
			input();
		}catch (NumberFormatException ne){
			System.out.println("You can input only number in port.");
			input();
		}
	}

	public void run()
	{
		String msg = null;
		try{
			while (true)
			{
				msg = dis.readLine();
				System.out.println(msg);
			}
		}catch (IOException ie){
			System.out.println("Server down or finishing from the client.");
			allClose();
			try{
				Thread.sleep(1000);
				System.exit(0);
			}catch (InterruptedException e){}
		}
	}

	private void speak()
	{
		String msg = "";
		try{
			dos.println(chatID);
			dos.flush();
			while ((msg = br.readLine()) != null)
			{
				dos.println(msg);
				dos.flush();
			}
		}catch (IOException ie){
			System.out.println("Server down or finishing from the client.");
			allClose();
			try{
				Thread.sleep(1000);
				System.exit(0);
			}catch (InterruptedException e){}
		}
	}

	private void allClose()
	{
		try{
			if(dos != null) dos.close();
			if(os != null) os.close();
			if(dis != null) dis.close();
			if(is != null) is.close();
			if(s != null) s.close();
		}catch (IOException ie){}
	}

	public static void main(String[] args) 
	{
		new TestClient();
	}
}
